package com.fenghongzhang.day008view;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

public class MyViewGroup extends ViewGroup {

    int left;
    int top;
    //当前所有view的总长度
    int currLen;
    public MyViewGroup(Context context) {
        super(context);
    }

    public MyViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childAt = getChildAt(i);
            //测量孩子
            measureChild(childAt,widthMeasureSpec,heightMeasureSpec);
        }
    }

    //控制子view的位置
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        //多少子空间
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childAt = getChildAt(i);
            if(i == 0){
                childAt.layout(left,top,childAt.getMeasuredWidth(),childAt.getMeasuredHeight());
                currLen = childAt.getMeasuredWidth();
                left = childAt.getMeasuredWidth();
                continue;
            }
            //第二个有几种情况.
            /**
             *
             * 1,如果不够长,就接着放.100,100 1080
             * 2,如果第一个够长. 那么第二个就另起一行.  1900 1080
             *
             */
            //一定要累加
            currLen += childAt.getMeasuredWidth();
            if(currLen < getMeasuredWidth()){
                //第二个
                childAt.layout(left,top,childAt.getMeasuredWidth()+left,childAt.getMeasuredHeight()+top);
                left += childAt.getMeasuredWidth();
            }else{
                //另起一行的时候.
                left = 0;
                currLen = childAt.getMeasuredWidth();
                top += childAt.getMeasuredHeight();
                childAt.layout(left,top,childAt.getMeasuredWidth()+left,childAt.getMeasuredHeight()+top);
                left += childAt.getMeasuredWidth();
            }

        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

    }
}
